<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">


















  
  
    
  
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.6/jquery.fancybox.min.css">







<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.1">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico?v=7.1.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico?v=7.1.1">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.1" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.1.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: true,
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="背景在日常线上运行的应用中如果报了异常，怎么在第一时间收到报错告警并且查看报错日志呢？周五就因为缺乏报错日志，导致构建服务受影响超过了 2 小时，虽然不至于「死人」，但是也确实让我意识到日志的重要性！后来临时在相关的地方加上日志，通过错误信息很快定位了到了原因，原来是数据库被运维人员做了新特性的改动，而我们服务还未适配好。想想当时的场景，还真是有点紧张~囧 今天就学习一下利用 Sentry 作为">
<meta name="keywords" content="log,log4j2,sentry">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring Boot 实战 —— 通过 Sentry 收集 Log4j2 异常日志记录">
<meta property="og:url" content="https://michael728.github.io/2019/08/11/java-spring-boot-sentry-log4j2/index.html">
<meta property="og:site_name" content="Michael翔">
<meta property="og:description" content="背景在日常线上运行的应用中如果报了异常，怎么在第一时间收到报错告警并且查看报错日志呢？周五就因为缺乏报错日志，导致构建服务受影响超过了 2 小时，虽然不至于「死人」，但是也确实让我意识到日志的重要性！后来临时在相关的地方加上日志，通过错误信息很快定位了到了原因，原来是数据库被运维人员做了新特性的改动，而我们服务还未适配好。想想当时的场景，还真是有点紧张~囧 今天就学习一下利用 Sentry 作为">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://gitee.com/michael_xiang/images/raw/master/xOgFTp.png">
<meta property="og:image" content="https://gitee.com/michael_xiang/images/raw/master/cTlup8.png">
<meta property="og:image" content="https://gitee.com/michael_xiang/images/raw/master/igfeN5.png">
<meta property="og:image" content="https://gitee.com/michael_xiang/images/raw/master/B625Ca.png">
<meta property="og:image" content="https://gitee.com/michael_xiang/images/raw/master/80Ncez.png">
<meta property="og:image" content="https://gitee.com/michael_xiang/images/raw/master/XoQY9F.png">
<meta property="og:image" content="https://gitee.com/michael_xiang/images/raw/master/zoG6sw.png">
<meta property="og:image" content="https://gitee.com/michael_xiang/images/raw/master/WWx2n1.png">
<meta property="og:image" content="https://gitee.com/michael_xiang/images/raw/master/VEi8nF.png">
<meta property="og:image" content="https://gitee.com/michael_xiang/images/raw/master/dgVaSQ.png">
<meta property="og:image" content="https://gitee.com/michael_xiang/images/raw/master/HyqIlX.png">
<meta property="og:updated_time" content="2020-01-05T15:47:56.120Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring Boot 实战 —— 通过 Sentry 收集 Log4j2 异常日志记录">
<meta name="twitter:description" content="背景在日常线上运行的应用中如果报了异常，怎么在第一时间收到报错告警并且查看报错日志呢？周五就因为缺乏报错日志，导致构建服务受影响超过了 2 小时，虽然不至于「死人」，但是也确实让我意识到日志的重要性！后来临时在相关的地方加上日志，通过错误信息很快定位了到了原因，原来是数据库被运维人员做了新特性的改动，而我们服务还未适配好。想想当时的场景，还真是有点紧张~囧 今天就学习一下利用 Sentry 作为">
<meta name="twitter:image" content="https://gitee.com/michael_xiang/images/raw/master/xOgFTp.png">



  <link rel="alternate" href="/atom.xml" title="Michael翔" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://michael728.github.io/2019/08/11/java-spring-boot-sentry-log4j2/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Spring Boot 实战 —— 通过 Sentry 收集 Log4j2 异常日志记录 | Michael翔</title>
  






  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?1c9958c951d5a7661571422e0340e156";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>







  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

  <meta name="referrer" content="never">
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Michael翔</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">因上努力，果上随缘！</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tools">

    
    
    
      
    

    

    <a href="/tools/" rel="section"><i class="menu-item-icon fa fa-fw fa-location-arrow"></i> <br>利器</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-books">

    
    
    
      
    

    

    <a href="/books" rel="section"><i class="menu-item-icon fa fa-fw fa-book"></i> <br>阅读</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-movies">

    
    
    
      
    

    

    <a href="/movies" rel="section"><i class="menu-item-icon fa fa-fw fa-film"></i> <br>观影</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-think">

    
    
    
      
    

    

    <a href="/think" rel="section"><i class="menu-item-icon fa fa-fw fa-lightbulb-o"></i> <br>一言</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    
  
  

  

  <a href="https://github.com/michael728" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewbox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a>



    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://michael728.github.io/2019/08/11/java-spring-boot-sentry-log4j2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Michael翔">
      <meta itemprop="description" content="DevOps CICD Blog 持续学习">
      <meta itemprop="image" content="/images/logo.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Michael翔">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Spring Boot 实战 —— 通过 Sentry 收集 Log4j2 异常日志记录

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-08-11 11:49:10" itemprop="dateCreated datePublished" datetime="2019-08-11T11:49:10+00:00">2019-08-11</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2020-01-05 15:47:56" itemprop="dateModified" datetime="2020-01-05T15:47:56+00:00">2020-01-05</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://gitee.com/michael_xiang/images/raw/master/xOgFTp.png" alt="Sentry-Robot"></p>
<h2 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h2><p>在日常线上运行的应用中如果报了异常，怎么在第一时间收到报错告警并且查看报错日志呢？周五就因为缺乏报错日志，导致构建服务受影响超过了 2 小时，虽然不至于「死人」，但是也确实让我意识到日志的重要性！后来临时在相关的地方加上日志，通过错误信息很快定位了到了原因，原来是数据库被运维人员做了新特性的改动，而我们服务还未适配好。想想当时的场景，还真是有点紧张~囧</p>
<p>今天就学习一下利用 <a href="https://sentry.io/welcome/" target="_blank" rel="noopener">Sentry</a> 作为日志收集系统，结合之前学习的 <a href="https://michael728.github.io/2019/08/17/java-spring-boot-log4j2/">log4j2</a> 日志输出，主动收集异常日志。</p>
<a id="more"></a>
<h2 id="Sentry"><a href="#Sentry" class="headerlink" title="Sentry"></a>Sentry</h2><p>我们先来 Sentry 是怎么介绍自己的：</p>
<blockquote>
<p>Open-source error tracking that helps developers monitor and fix crashes in real time. Iterate continuously. Boost efficiency. Improve user experience</p>
</blockquote>
<p>大体意思就是：Sentry 是一款开源的错误跟踪系统，可帮助开发人员实时监控和修复崩溃。它是不断迭代的，提高效率，改善用户体验。Sentry 本身的文档也记载的比较全面，强烈安利，一般问题可以通过阅读 <a href="https://docs.sentry.io/" target="_blank" rel="noopener">Doc</a> 学习或者<a href="https://forum.sentry.io/" target="_blank" rel="noopener">论坛咨询</a>。</p>
<p>OK，下面我们就开始通过 Docker 安装 Sentry。</p>
<p>PS：如果你的 Docker 环境还未配置好，可以阅读我之前的总结：<a href="https://michael728.github.io/2019/06/01/docker-centos-install/">Linux——CentOS 安装 Docker 教程</a></p>
<h3 id="前提"><a href="#前提" class="headerlink" title="前提"></a>前提</h3><p>在 <a href="https://docs.sentry.io/server/installation/" target="_blank" rel="noopener">Sentry Installation 页面</a>，官方做了总结，Sentry 需要和几个服务有交互：</p>
<ul>
<li><a href="http://www.postgresql.org/" target="_blank" rel="noopener">PostgreSQL</a>：Docker image <a href="https://hub.docker.com/_/postgres/" target="_blank" rel="noopener">postgres:9.5</a>，这里明确版本是 9.5，我觉得非常棒！这保证了在未来部署的可重现，避免了不同版本差异造成部署失败的问题。</li>
<li><a href="https://redis.io/" target="_blank" rel="noopener">Redis</a><ul>
<li>官方说如果你使用的 Ubuntu &lt; 15.04，推荐安装 <a href="https://launchpad.net/~chris-lea/+archive/ubuntu/redis-server" target="_blank" rel="noopener">chirs-lea/redis-server</a></li>
<li>文档推荐的是 Docker image <a href="https://hub.docker.com/_/redis/" target="_blank" rel="noopener">redis:3.2-alpine</a>.</li>
</ul>
</li>
</ul>
<p>硬件要求，具体的可以阅读<a href="https://docs.sentry.io/server/installation/#hardware" target="_blank" rel="noopener">官方文档</a>，我这里仅仅是家里测试使用，因此无所谓。</p>
<p>下面的步骤其实是官方文档的翻译，但是，跟着走了一遍之后发现，服务并不能正常运行起来，但是也没啥坏处，主要步骤其实就和这个差不多，可能是某些细节漏了，因此，你可以大体浏览一下步骤。如果不想浪费时间，可以直接跳到下面的 「脚本一键安装 Sentry」小节。</p>
<h3 id="创建容器"><a href="#创建容器" class="headerlink" title="创建容器"></a>创建容器</h3><p>需要 <a href="https://www.docker.com/get-started" target="_blank" rel="noopener">Docker 版本 1.10+</a></p>
<p>克隆仓库 <a href="https://github.com/getsentry/onpremise" target="_blank" rel="noopener">getsentry/onpremise</a>。这个仓库是定制化构建你自己 Sentry 镜像的基础：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">cd /data</span><br><span class="line">git clone https://github.com/getsentry/onpremise.git</span><br><span class="line">cd onpremise</span><br></pre></td></tr></table></figure>
<p>仓库里的 <code>sentry.conf.py and config.yml</code> 可供你 <a href="https://docs.sentry.io/server/config/" target="_blank" rel="noopener">配置 Sentry</a> 所用，建议先浏览一下这个配置文档。</p>
<p>现在开始构建我们定制好的镜像。如果你构建的镜像需要推送到你本地的镜像仓中，那么可以用如下方式先定义好镜像名再构建：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">REPOSITORY=registry.michael.com/sentry make build push</span><br></pre></td></tr></table></figure>
<p>我本地没有镜像仓，只需要用如下方式构建即可：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">make build</span><br></pre></td></tr></table></figure>
<h3 id="运行依赖的服务"><a href="#运行依赖的服务" class="headerlink" title="运行依赖的服务"></a>运行依赖的服务</h3><p>Redis:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">docker run \</span><br><span class="line">  --detach \</span><br><span class="line">  --name sentry-redis \</span><br><span class="line">  redis:3.2-alpine</span><br></pre></td></tr></table></figure>
<p>PostgreSQL:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">docker run \</span><br><span class="line">  --detach \</span><br><span class="line">  --name sentry-postgres \</span><br><span class="line">  --env POSTGRES_PASSWORD=secret \</span><br><span class="line">  --env POSTGRES_USER=sentry \</span><br><span class="line">  postgres:9.5</span><br></pre></td></tr></table></figure>
<p>Outbound Email:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">docker run \</span><br><span class="line">  --detach \</span><br><span class="line">  --name sentry-smtp \</span><br><span class="line">  tianon/exim4</span><br></pre></td></tr></table></figure>
<h3 id="运行-Sentry-服务"><a href="#运行-Sentry-服务" class="headerlink" title="运行 Sentry 服务"></a>运行 Sentry 服务</h3><p><code>${REPOSITORY}</code> 只的是你刚刚定义的镜像名，如果没有，默认是 <code>sentry-onpremise</code>。</p>
<p><img src="https://gitee.com/michael_xiang/images/raw/master/cTlup8.png" alt="REPOSITORY"></p>
<p>为了测试镜像是 OK 的，可以运行如下命令:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">docker run \</span><br><span class="line">  --rm $&#123;REPOSITORY&#125; \</span><br><span class="line">  --help</span><br></pre></td></tr></table></figure>
<p>现在可以生成一个 <code>secret-key</code> 值：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">docker run \</span><br><span class="line">  --rm $&#123;REPOSITORY&#125; \</span><br><span class="line">  config generate-secret-key</span><br></pre></td></tr></table></figure>
<p>生成的值可以在 <code>config.yml</code> 中设置给 <code>system.secret-key</code>,或者通过环境变量。如果是设置在 <code>config.yml</code> 文件中，这时候你必须重新构建你的镜像。</p>
<p>运行的基本命令举例如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">docker run \</span><br><span class="line">  --detach \</span><br><span class="line">  --link sentry-redis:redis \</span><br><span class="line">  --link sentry-postgres:postgres \</span><br><span class="line">  --link sentry-smtp:smtp \</span><br><span class="line">  --env SENTRY_SECRET_KEY='&lt;secret-key&gt;' \</span><br><span class="line"><span class="meta">  $</span>&#123;REPOSITORY&#125; \</span><br><span class="line">  &lt;command&gt;</span><br></pre></td></tr></table></figure>
<div class="note warning">
            <p>官方文档里有一行小字，说明的是后面的文档，不会特地的写上 –link 去表示链接容器，但是这些都是必须的！同时，${REPOSITORY} 会被引用为 sentry-onpremise。</p>
          </div>
<h4 id="运行-Web-服务"><a href="#运行-Web-服务" class="headerlink" title="运行 Web 服务"></a>运行 Web 服务</h4><p>暴露的是 9000 的端口，这样部署之后，可以通过 <code>http://localhost:9000/</code> 访问。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">docker run \</span><br><span class="line">  --detach \</span><br><span class="line">  --link sentry-redis:redis \</span><br><span class="line">  --link sentry-postgres:postgres \</span><br><span class="line">  --link sentry-smtp:smtp \</span><br><span class="line">  --name sentry-web \</span><br><span class="line">  --publish 9000:9000 \</span><br><span class="line">  --env SENTRY_SECRET_KEY=$&#123;SENTRY_SECRET_KEY&#125; \</span><br><span class="line">  sentry-onpremise \</span><br><span class="line">  run web</span><br></pre></td></tr></table></figure>
<h3 id="脚本一键安装-Sentry"><a href="#脚本一键安装-Sentry" class="headerlink" title="脚本一键安装 Sentry"></a>脚本一键安装 Sentry</h3><p>发现了 <a href="https://github.com/getsentry/onpremise/blob/master/install.sh" target="_blank" rel="noopener">getsentry/onpremise/install.sh</a> 这个脚本，看懂这个脚本里的内容基本上就差不多知道安装步骤了。</p>
<p>读一下脚本：</p>
<ul>
<li><code>LATEST_STABLE_SENTRY_IMAGE=&#39;sentry:9.1.2&#39;</code> 安装的是 <code>sentry:9.1.2</code></li>
<li>在 <code>docker-compose.yml</code> 中会去创建两个卷，分别是 <code>sentry-data</code>和 <code>sentry-postgres</code>，这和上面步骤是不是发现区别了，上面创建<br><code>postgres</code> 时，可没有创建卷；</li>
<li><code>cp -n .env.example &quot;$ENV_FILE&quot;</code> 会将仓库下的 <a href="https://github.com/getsentry/onpremise/blob/master/.env.example" target="_blank" rel="noopener">.env.example</a> 文件重命名为 <code>.env</code> 文件，其实里面就是为了设置一个环境变量 <code>SENTRY_SECRET_KEY</code></li>
<li><code>export SENTRY_IMAGE=$LATEST_STABLE_SENTRY_IMAGE</code> 命名了一个环境变量，记录了镜像名</li>
<li><code>docker-compose build</code> 开始构建镜像啦，其实就是类似这个命令 <code>docker build .</code></li>
<li><code>SECRET_KEY=$(docker-compose run --rm web config generate-secret-key 2&gt; /dev/null | tail -n1 | sed -e &#39;s/[\/&amp;]/\\&amp;/g&#39;)</code> 运行命令获得 <code>secret-key</code> 值，赋值给了变量 <code>SECRET_KEY</code></li>
<li><code>sed -i -e &#39;s/^SENTRY_SECRET_KEY=.*$/SENTRY_SECRET_KEY=&#39;&quot;$SECRET_KEY&quot;&#39;/&#39; $ENV_FILE</code> 将 <code>SECRET_KEY</code> 变量值填写到环境变量文件 <code>.env</code> 中</li>
<li>接着就是设置数据库的步骤，这其实是就是为了在数据库中添加账号数据和其他一些数据表生成</li>
<li>最后就是执行 <code>cleanup</code> 函数</li>
</ul>
<p>执行脚本之前，我们先把之前创建的几个服务删除掉吧：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">docker stop sentry-smtp sentry-postgres sentry-redis</span><br><span class="line">docker rm $(docker ps -aq)</span><br></pre></td></tr></table></figure>
<h4 id="配置邮箱"><a href="#配置邮箱" class="headerlink" title="配置邮箱"></a>配置邮箱</h4><p>通过上面的阅读，可以发现，运行脚本时，会去执行 <code>docker build .</code>，这个会将配置文件 <code>config.yml</code> 和环境变量 <code>.env</code> 放入镜像的。因此，我们启用发生异常时获取邮箱告警的功能，需要现在配置文件中设置好邮箱配置。</p>
<p>这里我们选择在 <code>.env</code> 中配置好环境变量，实现邮箱的配置：<br>配置 <code>config.yml</code>:</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">SENTRY_SECRET_KEY=)g=lkl1)uugx236%#)mq2o34^@a&amp;g3q85q**co*hbapm5y1*bs</span></span><br><span class="line"><span class="comment"># 邮箱设置</span></span><br><span class="line"><span class="string">SENTRY_EMAIL_HOST=smtp.qq.com</span></span><br><span class="line"><span class="string">SENTRY_EMAIL_USER=649168982@qq.com</span></span><br><span class="line"><span class="string">SENTRY_SERVER_EMAIL=649168982@qq.com</span></span><br><span class="line"><span class="comment"># 这里指的是邮箱的授权码，而非密码</span></span><br><span class="line"><span class="string">SENTRY_EMAIL_PASSWORD=xxxx</span></span><br><span class="line"><span class="string">SENTRY_EMAIL_USE_TLS=true</span></span><br><span class="line"><span class="string">SENTRY_EMAIL_PORT=587</span></span><br></pre></td></tr></table></figure>
<ul>
<li>网上的教程，大多数是 <code>SENTRY_EMAIL_HOST: &#39;smtp.exmail.qq.com&#39;</code>,这个是企业邮箱，我们个人的不这么设置。</li>
<li><code>SENTRY_EMAIL_USER</code> 和 <code>SENTRY_SERVER_EMAIL</code> 要保持一致；</li>
</ul>
<p>这里我设置 1 分钟，就能及时收到邮箱，但是设置 5 分钟，等了 5 分钟，也没收到，不知道是何原因：</p>
<p><img src="https://gitee.com/michael_xiang/images/raw/master/igfeN5.png" alt="Project-Alerts"></p>
<p><img src="https://gitee.com/michael_xiang/images/raw/master/B625Ca.png" alt="Alerts"></p>
<p>经过上面的设置，可以试试邮箱发送功能是否 OK：点击左上角头像，选择 <code>Admin</code>-》<code>Mail</code>-》<code>测试设置</code></p>
<p><img src="https://gitee.com/michael_xiang/images/raw/master/80Ncez.png" alt="邮箱测试"></p>
<h4 id="部署-sentry"><a href="#部署-sentry" class="headerlink" title="部署 sentry"></a>部署 sentry</h4><p>下面开始安装步骤：</p>
<ul>
<li><code>sh install.sh</code> 执行安装脚本，脚本执行完需要一点时间，运行完成之后，会退出。中间过程会让你选择是否创建账号：</li>
</ul>
<p><img src="https://gitee.com/michael_xiang/images/raw/master/XoQY9F.png" alt="添加账号"></p>
<ul>
<li>接着运行 <code>docker-compose up -d</code> 即可；</li>
</ul>
<p><img src="https://gitee.com/michael_xiang/images/raw/master/zoG6sw.png" alt="容器列表"></p>
<p>PS：为何容器的名称是都是 <code>onpremise</code> 开头的呢？<a href="https://docs.docker.com/compose/reference/overview/" target="_blank" rel="noopener">因为不指定名称时，会默认取目录名的</a>。</p>
<p>这时候输入刚刚创建的账号登录：</p>
<p><img src="https://gitee.com/michael_xiang/images/raw/master/WWx2n1.png" alt="login"></p>
<h2 id="配置-Sentry"><a href="#配置-Sentry" class="headerlink" title="配置 Sentry"></a>配置 Sentry</h2><h3 id="创建-project"><a href="#创建-project" class="headerlink" title="创建 project"></a>创建 project</h3><p>那我之前的 log4j2 的 demo 作为演示，这里选择一个 Java 项目，并且，我还创建了一个叫 <code>spring-boot</code> 的 Team。</p>
<p><img src="https://gitee.com/michael_xiang/images/raw/master/VEi8nF.png" alt="project"></p>
<h2 id="spring-boot-项目适配"><a href="#spring-boot-项目适配" class="headerlink" title="spring-boot 项目适配"></a>spring-boot 项目适配</h2><p><a href="https://docs.sentry.io/clients/java/" target="_blank" rel="noopener">官方文档-Java</a> 给出了适用于 Java 项目的全面的适配指南，咱们使用的是 <a href="https://docs.sentry.io/clients/java/integrations/#log4j-2x" target="_blank" rel="noopener">log4j2</a>。</p>
<h3 id="引入依赖"><a href="#引入依赖" class="headerlink" title="引入依赖"></a>引入依赖</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>io.sentry<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>sentry-log4j2<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.7.26<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="log4j2-xml-配置修改"><a href="#log4j2-xml-配置修改" class="headerlink" title="log4j2.xml 配置修改"></a>log4j2.xml 配置修改</h3><ul>
<li><code>configuration</code> 中加上 <code>packages=&quot;org.apache.logging.log4j.core,io.sentry.log4j2&quot;</code></li>
</ul>
<p>下面示例中的 <code>SentryAppender</code> 表示发送 <code>warn</code> 级别的日志到 Sentry Server。<code>ConsoleAppender</code> 仅仅表示是一个示例，表示你项目中之前使用的非 sentryappener 的例子。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">configuration</span> <span class="attr">status</span>=<span class="string">"warn"</span> <span class="attr">packages</span>=<span class="string">"org.apache.logging.log4j.core,io.sentry.log4j2"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">appenders</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">Console</span> <span class="attr">name</span>=<span class="string">"Console"</span> <span class="attr">target</span>=<span class="string">"SYSTEM_OUT"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">PatternLayout</span> <span class="attr">pattern</span>=<span class="string">"%d&#123;HH:mm:ss.SSS&#125; [%t] %-5level %logger&#123;36&#125; - %msg%n"</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">Console</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">Sentry</span> <span class="attr">name</span>=<span class="string">"Sentry"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">appenders</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">loggers</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">root</span> <span class="attr">level</span>=<span class="string">"INFO"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">appender-ref</span> <span class="attr">ref</span>=<span class="string">"Console"</span> /&gt;</span></span><br><span class="line">            <span class="comment">&lt;!-- Note that the Sentry logging threshold is overridden to the WARN level --&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">appender-ref</span> <span class="attr">ref</span>=<span class="string">"Sentry"</span> <span class="attr">level</span>=<span class="string">"WARN"</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">root</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">loggers</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>经过测试，，因为原有项目中的 apppender 都是为了之前的作用设置的，比如控制台打印、比如输出到文件。要想将异常信息发送到 Sentry，这里的<code>SentryAppender</code> 是必不可少的。别忘了 <code>appender-ref</code> 也要设置！</p>
<h3 id="配置-DSN"><a href="#配置-DSN" class="headerlink" title="配置 DSN"></a>配置 DSN</h3><p><a href="https://docs.sentry.io/clients/java/config/#configuration" target="_blank" rel="noopener">配置页面</a> 介绍了如何设置 DSN（Data Source Name）。</p>
<p> 进入 Sentry，项目的 DSN 在项目页面-》setings-》Clinet Keys(DSN) 中可以发现：</p>
<p><img src="https://gitee.com/michael_xiang/images/raw/master/dgVaSQ.png" alt="DSN"></p>
<p>配置 DSN 有好几种方式，具体的可以在页面查看，这里介绍我采用的：</p>
<p>在 <code>resources</code> 文件夹下，新建 <code>sentry.properties</code>：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">dsn=http://8d53042c89774e5dba599ee67c5c8804@192.168.3.43:9000/3</span><br></pre></td></tr></table></figure>
<div class="note warning">
            <p>默认的就是 <code>sentry.properties</code>，一开始我直接写在了 <code>application.properties</code> 中，Sentry 怎么也收不到异常日志。</p>
          </div>
<h3 id="代码中"><a href="#代码中" class="headerlink" title="代码中"></a>代码中</h3><p>代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.apache.logging.log4j.LogManager;</span><br><span class="line"><span class="keyword">import</span> org.apache.logging.log4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.apache.logging.log4j.Marker;</span><br><span class="line"><span class="keyword">import</span> org.apache.logging.log4j.MarkerManager;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyClass</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger logger = LogManager.getLogger(MyClass.class);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Marker MARKER = MarkerManager.getMarker(<span class="string">"myMarker"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">logSimpleMessage</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// This sends a simple event to Sentry</span></span><br><span class="line">        logger.error(<span class="string">"This is a test"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">logWithBreadcrumbs</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// Record a breadcrumb that will be sent with the next event(s),</span></span><br><span class="line">        <span class="comment">// by default the last 100 breadcrumbs are kept.</span></span><br><span class="line">        Sentry.record(</span><br><span class="line">            <span class="keyword">new</span> BreadcrumbBuilder().setMessage(<span class="string">"User made an action"</span>).build()</span><br><span class="line">        );</span><br><span class="line"></span><br><span class="line">        <span class="comment">// This sends a simple event to Sentry</span></span><br><span class="line">        logger.error(<span class="string">"This is a test"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">logWithTag</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// This sends an event with a tag named 'log4j2-Marker' to Sentry</span></span><br><span class="line">        logger.error(MARKER, <span class="string">"This is a test"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">logWithExtras</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// MDC extras</span></span><br><span class="line">        ThreadContext.put(<span class="string">"extra_key"</span>, <span class="string">"extra_value"</span>);</span><br><span class="line">        <span class="comment">// NDC extras are sent under 'log4j2-NDC'</span></span><br><span class="line">        ThreadContext.push(<span class="string">"Extra_details"</span>);</span><br><span class="line">        <span class="comment">// This sends an event with extra data to Sentry</span></span><br><span class="line">        logger.error(<span class="string">"This is a test"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">logException</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            unsafeMethod();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="comment">// This sends an exception event to Sentry</span></span><br><span class="line">            logger.error(<span class="string">"Exception caught"</span>, e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">unsafeMethod</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> UnsupportedOperationException(<span class="string">"You shouldn't call this!"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以发现，Sentry 使用的接口和之前 log4j2 是有区别的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 原来</span></span><br><span class="line"><span class="keyword">import</span> org.slf4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Logger log = LoggerFactory.getLogger(<span class="keyword">this</span>.getClass());</span><br><span class="line"><span class="comment">// sentry</span></span><br><span class="line"><span class="keyword">import</span> org.apache.logging.log4j.LogManager;</span><br><span class="line"><span class="keyword">import</span> org.apache.logging.log4j.Logger;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Logger log = LogManager.getLogger(<span class="keyword">this</span>.getClass());</span><br></pre></td></tr></table></figure>
<p>实际过程中，这里是很多人忽视的，一定要仔细一点！</p>
<p>这时候，使用我们之前的错误接口故意打印错误日志，看看 Sentry 的捕获效果吧：</p>
<p><img src="https://gitee.com/michael_xiang/images/raw/master/HyqIlX.png" alt="error"></p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>今天在之前加入的一个技术微信群里，一位同学发了一篇怎么搭建 Zabbix 的文章，被群主踢了。后来大家讨论，这种搭建的文章，普遍质量比较低，没有太多分享的意义，应该要更多的关注一些前言的知识、或者底层的基础知识。这种观点我是比较认同的，但是谁不是一步一步慢慢来的呢？</p>
<p>今天搭建 Sentry 的过程，对之前 docker-compose 的用法又有了进一步的认识，学习到了使用 <code>.env</code> 的方式设置容器内环境变量的方式，同时，也学习到了可以公用一种配置，让 docker-compose 文件内多个服务公用的方式。其实，自己的每一点的折腾，都会是后面的基石。只要持续积累，才会越走越顺！</p>
<h2 id="示例代码"><a href="#示例代码" class="headerlink" title="示例代码"></a>示例代码</h2><ul>
<li><a href="https://github.com/Michael728/awesome-spring-boot-examples/tree/master/spring-boot-log4j2" target="_blank" rel="noopener">awesome-spring-boot-examples/log4j2</a></li>
</ul>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="https://thinkhard.tech/2019/05/25/docker-sentry-deploy/" target="_blank" rel="noopener">神奇的展示-用 Docker 部署 Sentry Bug 日志收集服务</a></li>
<li><a href="https://juejin.im/post/5b226cbe51882574d02f9f62" target="_blank" rel="noopener">掘金-搭建私有的前端监控服务: sentry</a></li>
<li><a href="https://www.baoguoxiao.com/2018/10/30/sentry-configuring-mail/" target="_blank" rel="noopener">sentry配置邮件</a></li>
<li><a href="https://segmentfault.com/q/1010000016563419" target="_blank" rel="noopener">自建sentry后，配置了邮件服务，但是还是收不到验证邮件？</a> 这个问题有参考意义，还是推荐通过环境变量的方式而不是 <code>config.yml</code> 配置邮箱</li>
</ul>

      
    </div>

    
      

  <div class="popular-posts-header">相关文章</div>
  <ul class="popular-posts">
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/2019/08/09/java-spring-boot-logback/" rel="bookmark">Spring Boot 实战 —— 日志框架 logback 的学习</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/2019/08/10/java-spring-boot-log4j2/" rel="bookmark">Spring Boot 实战 —— 日志框架 Log4j2 SLF4J 的学习</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/2019/07/13/java-generic/" rel="bookmark">Java 泛型知识笔记</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/2019/07/07/java-spring-boot-hello-world/" rel="bookmark">Spring Boot 实战 —— 入门</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/2019/07/20/java-spring-boot-mybatis/" rel="bookmark">Spring Boot 实战 —— MyBatis（注解版）使用方法</a></div>
      
    </li>
  
  </ul>


    

    
    
    

    
      <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center;">
  <img id="wechat_subscriber_qcode" src="/images/wechat-qcode.jpg" alt="Michael翔 wechat" style="width: 200px; max-width: 100%;">
  <div>欢迎订阅 ヾﾉ≧∀≦)o</div>
</div>

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div>我知道是不会有人点的，但万一有人想不开呢👇</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="Michael翔 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.png" alt="Michael翔 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    
      <div>
        




  



<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Michael翔</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    
    <a href="https://michael728.github.io/2019/08/11/java-spring-boot-sentry-log4j2/" title="Spring Boot 实战 —— 通过 Sentry 收集 Log4j2 异常日志记录">https://michael728.github.io/2019/08/11/java-spring-boot-sentry-log4j2/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/DevOps/" rel="tag"># DevOps</a>
          
            <a href="/tags/Java/" rel="tag"># Java</a>
          
            <a href="/tags/Spring-Boot/" rel="tag"># Spring Boot</a>
          
            <a href="/tags/日志/" rel="tag"># 日志</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/08/10/java-spring-boot-log4j2/" rel="next" title="Spring Boot 实战 —— 日志框架 Log4j2 SLF4J 的学习">
                <i class="fa fa-chevron-left"></i> Spring Boot 实战 —— 日志框架 Log4j2 SLF4J 的学习
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/08/14/cicd-elk-install/" rel="prev" title="DevOps 之 ELK 基础设施搭建">
                DevOps 之 ELK 基础设施搭建 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yODgyMC81Mzkw" "></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/logo.jpg" alt="Michael翔">
            
              <p class="site-author-name" itemprop="name">Michael翔</p>
              <div class="site-description motion-element" itemprop="description">DevOps CICD Blog 持续学习</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">82</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">19</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">95</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/Michael728" title="GitHub &rarr; https://github.com/Michael728" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://weibo.com/1838446070/profile?topnav=1&wvr=6" title="微博 &rarr; https://weibo.com/1838446070/profile?topnav=1&wvr=6" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>微博</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.cnblogs.com/michael-xiang/" title="博客园 &rarr; https://www.cnblogs.com/michael-xiang/" rel="noopener" target="_blank"><i class="fa fa-fw fa-globe"></i>博客园</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.zhihu.com/people/michaelXoX" title="知乎 &rarr; https://www.zhihu.com/people/michaelXoX" rel="noopener" target="_blank"><i class="fa fa-fw fa-globe"></i>知乎</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://twitter.com/728_michael" title="Twitter &rarr; https://twitter.com/728_michael" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://t.me/michaelxiang" title="Telegram &rarr; https://t.me/michaelxiang" rel="noopener" target="_blank"><i class="fa fa-fw fa-telegram"></i>Telegram</a>
                </span>
              
            </div>
          

          
             <div class="cc-license motion-element" itemprop="license">
              
              
                
              
              
              
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
             </div>
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                关注列表
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://michael728.github.io/2018/09/16/blog-interesting/" title="https://michael728.github.io/2018/09/16/blog-interesting/">Blog List</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://zcheng.ren/posts/" title="https://zcheng.ren/posts/" rel="noopener" target="_blank">ZeeCoder</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://ehlxr.me/" title="https://ehlxr.me/" rel="noopener" target="_blank">ehlxr</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.kawabangga.com/" title="https://www.kawabangga.com/" rel="noopener" target="_blank">卡瓦邦噶-蚂蚁SRE</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.stdioa.com/" title="https://blog.stdioa.com/" rel="noopener" target="_blank">David Dai</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://bestzuo.cn/" title="https://bestzuo.cn/" rel="noopener" target="_blank">Sanarous</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.zhyong.cn/" title="https://www.zhyong.cn/" rel="noopener" target="_blank">ZhangYong-爱折腾软件</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.dalaoyang.cn/" title="https://www.dalaoyang.cn/" rel="noopener" target="_blank">Dalaoyang-SpringBoot</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.wuliaole.com/index.html" title="http://www.wuliaole.com/index.html" rel="noopener" target="_blank">无聊小博</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://ilovey.live/" title="http://ilovey.live/" rel="noopener" target="_blank">低调小熊猫-Java开发</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://michael728.github.io/2016/09/03/blog-logfile/" title="https://michael728.github.io/2016/09/03/blog-logfile/">建站日志</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#背景"><span class="nav-number">1.</span> <span class="nav-text">背景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Sentry"><span class="nav-number">2.</span> <span class="nav-text">Sentry</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#前提"><span class="nav-number">2.1.</span> <span class="nav-text">前提</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建容器"><span class="nav-number">2.2.</span> <span class="nav-text">创建容器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#运行依赖的服务"><span class="nav-number">2.3.</span> <span class="nav-text">运行依赖的服务</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#运行-Sentry-服务"><span class="nav-number">2.4.</span> <span class="nav-text">运行 Sentry 服务</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#运行-Web-服务"><span class="nav-number">2.4.1.</span> <span class="nav-text">运行 Web 服务</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#脚本一键安装-Sentry"><span class="nav-number">2.5.</span> <span class="nav-text">脚本一键安装 Sentry</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#配置邮箱"><span class="nav-number">2.5.1.</span> <span class="nav-text">配置邮箱</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#部署-sentry"><span class="nav-number">2.5.2.</span> <span class="nav-text">部署 sentry</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#配置-Sentry"><span class="nav-number">3.</span> <span class="nav-text">配置 Sentry</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建-project"><span class="nav-number">3.1.</span> <span class="nav-text">创建 project</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#spring-boot-项目适配"><span class="nav-number">4.</span> <span class="nav-text">spring-boot 项目适配</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#引入依赖"><span class="nav-number">4.1.</span> <span class="nav-text">引入依赖</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#log4j2-xml-配置修改"><span class="nav-number">4.2.</span> <span class="nav-text">log4j2.xml 配置修改</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#配置-DSN"><span class="nav-number">4.3.</span> <span class="nav-text">配置 DSN</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#代码中"><span class="nav-number">4.4.</span> <span class="nav-text">代码中</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">5.</span> <span class="nav-text">总结</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#示例代码"><span class="nav-number">6.</span> <span class="nav-text">示例代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考"><span class="nav-number">7.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 – <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Michael翔</span>

  

  
</div>









        








        
      </div>
    </footer>

    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  



  
    
    
      
    
  
  <script color="0,0,255" opacity="0.5" zindex="-1" count="99" src="//cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-nest@1.0.0/canvas-nest.min.js"></script>













  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.6/jquery.fancybox.min.js"></script>


  


  <script src="/js/utils.js?v=7.1.1"></script>

  <script src="/js/motion.js?v=7.1.1"></script>



  
  


  <script src="/js/affix.js?v=7.1.1"></script>

  <script src="/js/schemes/pisces.js?v=7.1.1"></script>




  
  <script src="/js/scrollspy.js?v=7.1.1"></script>
<script src="/js/post-details.js?v=7.1.1"></script>



  


  <script src="/js/next-boot.js?v=7.1.1"></script>


  

  

  

  


  
    <script>
  window.livereOptions = {
    refer: '2019/08/11/java-spring-boot-sentry-log4j2/'
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
</script>

  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
  

  
  

  


  

  

  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>


  

  

  

  

  

  
<script>
  $('.highlight').not('.gist .highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
